"""
@author: dfy
@file: conn_mysql.py
@time: 2024/8/25 17:32
"""

import pymysql
import redis
import json

db = pymysql.connect(
    user = "deco",
    password= "deco123",
    host="192.168.178.133",
    database="sc"
)

cursor = db.cursor()
# cursor.execute("select * from user_info where username='sc2';")
# data = cursor.fetchall()
# print(data)



# 创建 Redis 连接
r = redis.Redis(host='192.168.178.133', port=6379, db=0)
# # 设置一个键值对
# r.set('name', 'value')
# # 获取键对应的值
# value = r.get('name')
# print(value.decode())   # 注意，返回的是字节对象，需要解码为字符串
# # 检查键是否存在
# exists = r.exists('name')
# print(exists)

# 写一个获取用户信息的函数  这个函数接收一个name
# def getInfo(name):
#     pass
# 写一个 缓存装饰器
#   name 作为redis的key
#   如果存在，直接返回
#   如果不存在，就执行原函数，从数据库获取信息，获取到的信息存到redis

def redis_decorator(func):
    def inner(name):
        try:
            result = r.get(name)
            if result:
                return result.decode()
            else:
                result_mysql = func(name)
                r.set(name, result_mysql)
                return result_mysql
        except Exception as e:
            print(f"Error in decorator: {e}")
    return inner

@redis_decorator
def getInfo(name):
    try:
        sql = f"select username,userage,useraddress from user_info where username = '{name}'"
        cursor.execute(sql)
        data = cursor.fetchone()
        data_dict = {
            "username": data[0],
            "userage": data[1],
            "useraddress": data[2]
        }
        json_data = json.dumps(data_dict)
        return json_data
    except Exception as e:
        print(f"Error in getInfo function: {e}")

print(getInfo('class'))